﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DTO;

namespace DAO
{
    public class TaiKhoanDangNhapDA
    {
        public static TaiKhoanDangNhap GetByID(int maID)
        {
            TaiKhoanDangNhap tk = null;
            SqlConnection cn = DataProvider.Connect();
            SqlCommand cmd = new SqlCommand("Proc_TaiKhoanDangNhap_GetById", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@maTK", maID));
            SqlDataReader dataReader = cmd.ExecuteReader();
            if (dataReader.Read())
            {
                tk = new TaiKhoanDangNhap();
                tk.MaTK = maID;
                string matKhau= Convert.ToString(dataReader["MatKhau"]);
                tk.MatKhau = matKhau.Trim();
                tk.NgayKichHoat = Convert.ToDateTime(dataReader["NgayDangNhap"]);
                tk.delFlg = Convert.ToInt32(dataReader["DelFlg"]);
                tk.TaiKhoanChinh = TaiKhoanChinhDA.GetByID(tk.MaTK);
                tk.ListLichSuTruyCap = LichSuTruyCapDA.GetByMaTaiKhoan(tk.MaTK);
            }
            cn.Close();
            return tk;
        }


        public static TaiKhoanDangNhap LayChiTietNguoiDung(int maTK, string matKhau, int type)
        {
            TaiKhoanDangNhap tk = null;
        
            SqlConnection cn = DataProvider.Connect();
            SqlCommand cmd = new SqlCommand("Proc_TaiKhoanDangNhap_Authentic", cn);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@maTK", maTK));

            cmd.Parameters.Add(new SqlParameter("@type", type));
            cmd.Parameters.Add(new SqlParameter("@pass", matKhau));
            SqlDataReader dataReader = cmd.ExecuteReader();

            if (dataReader.Read())
            {
                tk = new TaiKhoanDangNhap();
                tk.MaTK = maTK;
                tk.MatKhau =matKhau ;
                tk.NgayKichHoat = Convert.ToDateTime(dataReader["NgayDangNhap"]);
                tk.delFlg = Convert.ToInt32(dataReader["DelFlg"]);
            }
            cn.Close();
            return tk;
        }

        public static void ThayDoiMatKhau(int maTK, string matKhau, int type)
        {
            SqlConnection cn = DataProvider.Connect();
            SqlCommand cmd = new SqlCommand("Proc_TaiKhoanDangNhap_ChangePassword", cn);
            cmd.CommandType = CommandType.StoredProcedure;

            cmd.Parameters.Add(new SqlParameter("@type", type));
            cmd.Parameters.Add(new SqlParameter("@maTK",maTK));
            cmd.Parameters.Add(new SqlParameter("@newPass", matKhau));
            cmd.ExecuteNonQuery();
            cn.Close();
        }
    }
}
